package com.srwl.mytx.fragment;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.UserManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.AuthTask;
import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.Helper;
import com.srwl.mytx.activity.BalanceStatementActivity;
import com.srwl.mytx.activity.DepositStatementActivity;
import com.srwl.mytx.activity.WithDrawRecordActivity;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.AuthResult;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.PayPasswordDialog;
import com.srwl.mytx.widget.RechargeDialogFragment;
import com.srwl.mytx.widget.WithdrawDialogFragment;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.CouponRecordActivity;
import com.srwl.mytx.activity.ReceivedDonationRecordActivity;
import com.srwl.mytx.activity.RechargeRecordActivity;
import com.srwl.mytx.activity.RetrievePayPasswordActivity;
import com.srwl.mytx.activity.TransferRecordActivity;
import com.srwl.mytx.R;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static android.app.Activity.RESULT_OK;

/**
 * A simple {@link } subclass.
 */
public class ChangeFragment extends BaseFragment implements View.OnClickListener {
    private static final String TAG = "ChangeFragment";
    private static final int SDK_AUTH_FLAG = 2;
    private TextView tv_changeDetails, tv_redPacketRecords, tv_managePayWord, tv_recharge, tv_changeBalance, tv_retrievePayPassword, tv_managePayLimit;
    private View line_four, line_5,line_6;
    public static final int REQUEST_CODE_RECHARGE = 1;
    private TextView tv_changeWithdraw, tv_customerService;
    private boolean haveLimit;//是否设置过支付密码
    private String oldPayPassword;//修改支付密码时候，输入额旧支付密码
    private ProgressBar progressBar;
    private TextView tv_deposit;
    private Integer originalPayLimit;
    private LocalBroadcastManager broadcastManager;
    private BroadcastReceiver receiver;

    public ChangeFragment() {
        // Required empty public constructor
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rp_fragment_change, container, false);
        initViewsAndEvents(view);
        return view;
    }


    protected void initViewsAndEvents(View view) {
        tv_deposit = view.findViewById(R.id.tv_deposit);
        progressBar = view.findViewById(R.id.progress_bar);
        tv_changeDetails = view.findViewById(R.id.tv_change_details);
        //tv_redPacketRecords = view.findViewById(R.id.tv_my_red_packet_records);
        tv_managePayWord = view.findViewById(R.id.tv_manage_pay_pwd);
        tv_managePayLimit = view.findViewById(R.id.tv_manage_pay_limit);
        tv_recharge = view.findViewById(R.id.tv_change_recharge);
        tv_changeWithdraw = view.findViewById(R.id.tv_change_withdraw);
        tv_changeBalance = view.findViewById(R.id.tv_change_balance);
        tv_retrievePayPassword = view.findViewById(R.id.tv_retrieve_pay_password);
        tv_customerService = view.findViewById(R.id.tv_customer_service);
        line_four = view.findViewById(R.id.line_four);
        line_5 = view.findViewById(R.id.line_5);
        line_6 = view.findViewById(R.id.line_6);
        User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
        tv_changeBalance.setText(Utils.moneyFormat(loginUserInfo.getBalance()));
        Double deposit = loginUserInfo.getDeposit();
        if (deposit == null || deposit == 0) {
            tv_deposit.setVisibility(View.GONE);
        } else {
            tv_deposit.setText("保证金 " + Utils.moneyFormat(deposit));
        }
        tv_changeDetails.setOnClickListener(this);
        //tv_redPacketRecords.setOnClickListener(this);
        tv_managePayWord.setOnClickListener(this);
        tv_recharge.setOnClickListener(this);
        tv_changeWithdraw.setOnClickListener(this);
        tv_managePayLimit.setOnClickListener(this);
        tv_retrievePayPassword.setOnClickListener(this);
        tv_customerService.setOnClickListener(this);
        /*view.findViewById(R.id.tv_received_donation_records).setOnClickListener(this);
        view.findViewById(R.id.tv_transfer_records).setOnClickListener(this);
        view.findViewById(R.id.tv_withdraw_record).setOnClickListener(this);*/
        view.findViewById(R.id.tv_deposit_statement).setOnClickListener(this);
        view.findViewById(R.id.tv_balance_statement).setOnClickListener(this);
        view.findViewById(R.id.tv_manage_pay_limit).setOnClickListener(this);
        originalPayLimit = UserProfileManager.getInstance().getLoginUserInfo().getPayLimit();
        setPayUi();
        initBroadCast();
    }

    private void initBroadCast() {
        broadcastManager = LocalBroadcastManager.getInstance(getContext());
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                User loginUserInfo = UserProfileManager.getInstance().getLoginUserInfo();
                tv_changeBalance.setText(Utils.moneyFormat(loginUserInfo.getBalance()));
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constant.ACTION_USER_INFO_CHANGE);
        broadcastManager.registerReceiver(receiver, intentFilter);
    }

    /**
     * 根据是否设置过支付密码，显示不同的ui
     */
    private void setPayUi() {
        haveLimit = UserProfileManager.getInstance().getLoginUserInfo().getPayLimit() != -1;
        if (haveLimit) {
            /*tv_managePayWord.setText("修改支付密码");
            tv_retrievePayPassword.setVisibility(View.VISIBLE);
            line_four.setVisibility(View.VISIBLE);
            tv_managePayLimit.setVisibility(View.VISIBLE);
            line_5.setVisibility(View.VISIBLE);*/
            //当设置过密码后就不显示"修改支付密码"的接口了，需要修改直接重置密码
            tv_managePayWord.setVisibility(View.GONE);
            line_6.setVisibility(View.GONE);
            line_5.setVisibility(View.VISIBLE);
            tv_retrievePayPassword.setVisibility(View.VISIBLE);
            line_four.setVisibility(View.VISIBLE);
            tv_managePayLimit.setVisibility(View.VISIBLE);

        } else {
            tv_managePayWord.setText("设置支付密码");
            //没设置支付密码钱，就去设置免密额度的话，要报错，先隐藏掉设置免密额度
            tv_managePayLimit.setVisibility(View.GONE);
            line_5.setVisibility(View.GONE);
        }
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        switch (i) {
            case R.id.tv_change_details:
                startActivity(new Intent(getContext(), RechargeRecordActivity.class));

                break;

           /* case R.id.tv_withdraw_record:
                startActivity(new Intent(getContext(), WithDrawRecordActivity.class));
                break;
            case R.id.tv_my_red_packet_records:
                startActivity(new Intent(getContext(), CouponRecordActivity.class));

                break;*/
            case R.id.tv_manage_pay_pwd:
                if (haveLimit) {
                    replacePayPassword();
                } else {
                    setUpPayPassword();
                }

                break;
            case R.id.tv_retrieve_pay_password:
                startActivity(new Intent(getContext(), RetrievePayPasswordActivity.class));

                break;
            case R.id.tv_change_recharge:
                final RechargeDialogFragment rechargeDialogFragment = RechargeDialogFragment.newInstance();
                rechargeDialogFragment.show(getFragmentManager(), "recharge");
                rechargeDialogFragment.setOnFragmentInteractionListener(new RechargeDialogFragment.OnFragmentInteractionListener() {
                    @Override
                    public void onRechargeSuccess(Double totalBalance) {
                        tv_changeBalance.setText(Utils.moneyFormat(totalBalance));
                        UserProfileManager.getInstance().setUserBalance(totalBalance);
                        rechargeDialogFragment.dismiss();

                        ChangeFragment.this.showToast(tv_recharge, "充值成功");
                    }

                    @Override
                    public void showToast(String message) {

                    }
                });


                // startActivity(new Intent(getActivity(), PayDemoActivity.class));


                break;
            case R.id.tv_change_withdraw:
//            if (checkIsAuthAlipay()) return;

                final WithdrawDialogFragment withdrawDialogFragment = WithdrawDialogFragment.newInstance();
                withdrawDialogFragment.show(getFragmentManager(), "withdraw");
                withdrawDialogFragment.setOnFragmentInteractionListener(new WithdrawDialogFragment.OnFragmentInteractionListener() {
                    @Override
                    public void onWithdrawSuccess(double balance) {
                        //showToast(tv_changeWithdraw, "提现申请已提交完成，请主意提现成功通知");
                        ConfirmDialog dialog = new ConfirmDialog(getActivity(), "提示", "提现申请已提交完成，请注意提现成功通知");
                        dialog.show();
                        tv_changeBalance.setText(Utils.moneyFormat(balance));
                    }
                });

                break;
            /*case R.id.tv_received_donation_records:
                startActivity(new Intent(getContext(), ReceivedDonationRecordActivity.class));

                break;*/
            /*case R.id.tv_transfer_records:
                startActivity(new Intent(getContext(), TransferRecordActivity.class));

                break;*/
            case R.id.tv_customer_service:
                contactCustomerService();

                break;

            case R.id.tv_balance_statement:
                startActivity(new Intent(getActivity(), BalanceStatementActivity.class));
                break;
            case R.id.tv_deposit_statement:
                startActivity(new Intent(getActivity(), DepositStatementActivity.class));
                break;
            case R.id.tv_manage_pay_limit:
                replacePayLimit();
                break;
        }
    }

    private void replacePayPassword() {
        PayPasswordDialog payPasswordDialog = new PayPasswordDialog(getActivity(), PayPasswordDialog.TYPE_INPUT_OLD_PAY_PASSWORD);
        payPasswordDialog.show();
        payPasswordDialog.setOnConfirmListener(new PayPasswordDialog.OnConfirmListener() {
            @Override
            public void onCommit(String passWord) {
                oldPayPassword = passWord;
                PayPasswordDialog payPasswordDialog = new PayPasswordDialog(getActivity(), PayPasswordDialog.TYPE_INPUT_NEW_PAY_PASSWORD);
                payPasswordDialog.show();
                payPasswordDialog.setOnSetPasswordListener(new PayPasswordDialog.OnSetPassWordListener() {
                    @Override
                    public void onCommit(String payPassWord, int payLimit) {
                        final Map<String, Object> info = new HashMap<>();//因为User 中没有 oldPayPassword的属性，所以数据就打包进Map 上传
                        info.put("oldPayPassword", oldPayPassword);
                        info.put("newPayPassword", payPassWord);
                        resetPayPassword(payLimit, info, originalPayLimit);
                    }
                });
            }
        });
    }

    private void replacePayLimit() {
        originalPayLimit = UserProfileManager.getInstance().getLoginUserInfo().getPayLimit();
        PayPasswordDialog payPasswordDialog = new PayPasswordDialog(getActivity(), PayPasswordDialog.TYPE_SET_PAY_LIMIT, originalPayLimit);
        payPasswordDialog.show();
        payPasswordDialog.setOnSetPasswordListener(((payPassWord, payLimit) -> {
            final Map<String, Object> info = new HashMap<>();
            /*info.put("oldPayPassword", payPassWord);
            info.put("newPayPassword", payPassWord);
            info.put("payLimit", payLimit);
            resetPayPassword(payLimit,info,originalPayLimit);*/
            info.put("payPassword", payPassWord);
            info.put("payLimit", payLimit);
            if (payLimit == originalPayLimit) {
                showToast_v1("免密额度未修改！");
                return;
            }
            setPasswordFreePayLimit(info);
        }));
    }

    void setPasswordFreePayLimit(Map<String, Object> info) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .setPasswordFreePaymentLimit(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || response == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (Constant.PAY_PASSWORD_ERROR == result.getStatus()) {
                                showToast("修改失败,支付密码错误!");
                            }
                            return;
                        }
                        UserProfileManager.getInstance().setPayLimit((Integer) info.get("payLimit"));
                        Log.d(TAG, "onResponse: 修改免密码支付额度成功");
                        showToast("修改免密码支付额度成功");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }


    void resetPayPassword(final int payLimit, Map<String, Object> info, final Integer oldLimit) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .modifyPayPassword(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            if (Constant.PAY_PASSWORD_ERROR == result.getStatus()) {
                                showToast("原支付密码错误");

                            }

                            return;
                        }
                        Log.d(TAG, "onResponse: 修改支付密码完成");

                        showToast("修改支付密码完成");

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    void setUpPayPassword() {
        PayPasswordDialog dialog = new PayPasswordDialog(getActivity(), PayPasswordDialog.TYPE_SET_PAY_PASSWORD);
        dialog.show();
        dialog.setOnSetPasswordListener(new PayPasswordDialog.OnSetPassWordListener() {
            @Override
            public void onCommit(String payPassWord, int payLimit) {

                savePayPassword(payPassWord, payLimit);
            }
        });
    }

    void savePayPassword(String payPassWord, int excusePassWordLimit) {
        final User user = new User();
        user.setPayLimit(excusePassWordLimit);
        user.setPayPassword(payPassWord);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .setPayPassword(user)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.SETUP_PAY_PASSWORD_REPEAT:
                                    showToast("已经设置过支付密码了");
                            }
                            return;
                        }
                        Log.d(TAG, "onResponse: 支付密码设置完成");
                        showToast("支付密码设置完成");
                        UserProfileManager.getInstance().syncLoginUserInfo(user);
                        setPayUi();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        showToast(getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    /**
     * 检查是否通过支付宝授权，是否绑定支付宝账户
     *
     * @return
     */
    private boolean checkIsAuthAlipay() {
        String aliAccount = UserProfileManager.getInstance().getLoginUserInfo().getAliAccount();
        //判断是否已经授权，是否有支付宝账户，如果是空的，弹出提示框，去绑定支付宝
        if (TextUtils.isEmpty(aliAccount)) {
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
            dialogBuilder.setTitle("提醒");
            dialogBuilder.setMessage(getString(R.string.ali_uid_is_empty));
            dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO: 2018/8/27 如果不考虑RSA2的秘钥更换的话，生成一个授权请求信息，可以一直使用，省了每次去服务端请求
//                    String authInfo = "app_name=mc&auth_type=AUTHACCOUNT&apiname=com.alipay.account.auth&biz_type=openservice&product_id=APP_FAST_LOGIN&scope=kuaijie&pid=2088002485871700&target_id=1535371275532&app_id=2018081961030912&sign_type=RSA2&sign=iiPjTq2dnCW1%2FMsdQPEMvyFEdE36T1VjmWEmIOQ83purg461wdM6atVBjvpH8M3B2ZK573ZqhJ41ujR%2F7cz2FBEGCW%2BOYF2LcfD7zIT2eyNHrruDLMjvjFWCePLwXDxSw4AkCjA8TmsgDk8EGR779qe2ArkZSBWVRO4c7q47VSP%2B3KP3%2FqNbYifTME3O5s5pgO9QGG2xZ4LgjgiQCJ5rS2DZcD3wVoHj78yFvJK0qKkx%2FsevL%2BEE3fAGUXs%2B9QY6qjiS3EOVDGVBXYFQtPZev2r7snRYvx1Y%2BqzVSmojock%2FuYK%2BRAaWn1E%2FPwW9WJpQKrSHdYRg6fD%2FTR5DlFX6Cw%3D%3D";
//                    authAlipay(authInfo);
                    JSONObject body = new JSONObject();
                    body.put("token", UserProfileManager.getInstance().getLoginUserInfo().getToken());
                    RetrofitManager.getInstance().createRequest(AliService.class)
                            .getAuthUrl(body)
                            .enqueue(new Callback<CommonResult>() {
                                @Override
                                public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                                    CommonResult result = response.body();
                                    if (!response.isSuccessful() || result == null) {
                                        Log.e(TAG, "获取授权链接出错 " + response.message());
                                        return;
                                    }
                                    if (result.isError()) {
                                        Log.e(TAG, "获取授权链接出错 " + result.getMsg());

                                        if (result.getStatus() == Constant.TOKEN_INVALID) {
                                            showToast(getString(R.string.login_expire));
                                        }
                                        return;
                                    }
                                    final String authInfo = (String) result.getData();
                                    Log.d(TAG, "获取授权链接完成 " + authInfo);
                                    authAlipay(authInfo);

                                }

                                @Override
                                public void onFailure(Call<CommonResult> call, Throwable t) {

                                }
                            });

                }
            });
            dialogBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialogBuilder.create().show();
            return true;
        }
        return false;
    }

    private void authAlipay(final String authInfo) {
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(getActivity());
                // 调用授权接口，获取授权结果
                Map<String, String> response = authTask.authV2(authInfo, true);
                String result1 = response.get("result");
                String resultStatus = response.get("resultStatus");
                switch (resultStatus) {
                    case "9000":
                        Log.i(TAG, "请求处理成功" + result1);
                        break;

                    case "6002":
                        Log.e(TAG, "网络连接出错");
                        return;
                    case "6001":
                        Log.e(TAG, "用户中途取消");
                        return;

                    case "4000":
                        Log.e(TAG, "系统异常");
                        return;
                    default:
                        Log.e(TAG, "其他错误");
                        return;

                }
                Log.i(TAG, response.toString());
                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = response;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    private void bindAliPay(final String authCode) {
        Map<String, String> info = new HashMap<>();
        info.put("auth_code", authCode);
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(AliService.class)
                .bindAliPay(info)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "绑定支付宝出错 " + response.message());
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "绑定支付宝出错 " + result.getMsg());

                            if (result.getStatus() == Constant.TOKEN_INVALID) {
                                showToast(getString(R.string.login_expire));
                            } else if (result.getStatus().equals(Constant.RETURN_HTTP_STATUS_ALI_USER_EXIST)) {
                                progressBar.setVisibility(View.GONE);
                                showToast(result.getMsg());


                            }
                            return;
                        }
                        Log.d(TAG, "绑定支付宝完成 ");
//                        //把授权信息，保存在本地
//                        JSONObject o = (JSONObject) result.getData();
//                        if (o.containsKey("userInfo")) {
//                            User originalUserInfo  = o.getObject("userInfo", User.class);
//                            Helper.getInstance().getUserProfileManager().syncLoginUserInfo(originalUserInfo);
//                        }else if (o.containsKey("aliUid")){
//                            String aliUid = o.getString("aliUid");
                        String aliAccount = (String) result.getData();
                        UserProfileManager.getInstance().setLoginUserAliAccount(aliAccount);
                        showToast(tv_changeWithdraw, "绑定成功");
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        showToast(tv_changeWithdraw, "系统错误");
                    }
                });

    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_RECHARGE) {


                Log.i("recharge", "充值成功");

            }
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        //  authResult.getAlipayOpenId();
                        // 传入，则支付账户为该授权账户
                        Log.i(TAG, "handleMessage: 授权成功");
                        bindAliPay(authResult.getAuthCode());
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(getActivity(),
                                "授权失败", Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }


    };

    void contactCustomerService() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        progressBar.setVisibility(View.VISIBLE);
        RetrofitManager.getInstance().createRequest(UserService.class)
                .customerService()
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        progressBar.setVisibility(View.GONE);
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(tv_customerService, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.d(TAG, "onResponse: " + result.getMsg());
                            return;
                        }

                        JSONObject object = (JSONObject) result.getData();
                        //把用户作为临时联系人 保存在数据库
                        User manualUser = object.toJavaObject(User.class);
                        manualUser.setType(Constant.USER_TYPE_TEMP);
                        DBManager.getInstance().getDaoSession().getUserDao().insertOrReplace(manualUser);
                        startActivity(new Intent(getActivity(), ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, manualUser));

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        showToast(tv_customerService, getString(R.string.system_busy));
                    }
                });
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        broadcastManager.unregisterReceiver(receiver);
    }
}
